const ClassIdRegex = /cls:(\w*)/;
const CalendarTitleRegex = /t=([^\s]+)/;

export class ClassBlock {

    public RawText: string;
    public static BlockTag = 'class';

    constructor(text: string) {
        this.RawText = text;

        this.build();
    }

    public static isClassBlock(text: string) {
        return text.startsWith('[cls:') && text.endsWith(']');
    }

    public id!: string;
    private title: string = '';
    private styles: { [key: string]: string; } = {};
    private isValid: boolean = true;

    /**
     * 解析原始文本并构建类块信息
     * 
     * 从RawText中提取ID、标题和样式：
     * 1. 使用正则匹配提取ID，若无效则标记为无效块
     * 2. 从去除首尾字符的文本中提取标题
     * 3. 解析剩余文本为键值对样式
     * 
     * @private 内部实现方法
     * @throws 处理异常时自动标记为无效块
     */
    private build() {
        const noWrapText = this.RawText.substring(1, this.RawText.length - 1);

        try { 
            this.id = ClassIdRegex.exec(this.RawText)?.[1] || '';
            if (!this.id) {
                this.isValid = false;
                return;
            }

            this.title = CalendarTitleRegex.exec(noWrapText)?.[1]!;

            const styles = noWrapText.split(' ').filter(item=>
                !item.startsWith('cls:') && !item.startsWith('t=')
            ).map(item=>item.split(':'));
            
            styles.forEach(item => {
                if (item.length === 2) {
                    this.styles[item[0]] = item[1];
                }
            });

        } catch (error) {
            this.isValid = false;
        }
    }

    /**
     * 获取类块数据
     * @returns 包含id、title和styles的对象
     */
    public getData() {
        return {
            id: this.id,
            title: this.title,
            styles: this.styles,
        };
    }
}
